/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.databinding.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.OnRebindCallback
import androidx.databinding.ViewDataBinding
import androidx.transition.TransitionManager
import com.lokiy.core.fragment.BasicFragment
import com.lokiy.databinding.BR
import com.lokiy.kit.ktx.getSuperclassTypeParameter

/**
 * DataBinding
 */
@Suppress("UNCHECKED_CAST")
abstract class DataBindingFragment<Binding : ViewDataBinding> : BasicFragment() {

    protected var binding: Binding? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val type = javaClass.getSuperclassTypeParameter(0) as Class<*>
        val declaredMethod = type.getDeclaredMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
        return (declaredMethod.invoke(null, layoutInflater, container, false) as Binding).also {
            it.setVariable(BR.ft, this)
            it.lifecycleOwner = this
            if (needAnim()) {
                it.addOnRebindCallback(object : OnRebindCallback<Binding>() {
                    override fun onPreBind(binding: Binding?): Boolean {
                        TransitionManager.beginDelayedTransition(binding?.root as ViewGroup? ?: return true)
                        return true
                    }
                })
            }
            binding = it
        }.root.also {
            it.isClickable = true
        }
    }

    open fun needAnim() = true

    override fun onDestroyView() {
        super.onDestroyView()
        binding?.unbind()
        binding = null
    }
}